<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleExport"
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="isShow = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="loading" style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            sortable
            type="index"
            width="100"
            :index="indexMethod"
          />
          <el-table-column prop="username" label="姓名" sortable />
          <el-table-column label="头像">
            <template #default="{ row }">
              <!-- {{ row.staffPhoto }} -->
              <img
                v-imgerror="errorImg"
                class="staff"
                :src="row.staffPhoto || defaultImg"
                alt=""
                @click="clickShowCodeDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable
            :formatter="formatEmployment"
          />
          <el-table-column prop="departmentName" label="部门" sortable />
          <el-table-column label="入职时间" sortable>
            <template #default="{ row }">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                :disabled="!checkBtnAccess('POINT_USER_EDIT')"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="handleRoleAssign(row.id)"
              >角色</el-button>
              <el-button
                type="text"
                size="small"
                :disabled="!checkBtnAccess('POINT_USER_DELETE')"
                @click="del(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-sizes="[1, 2, 3, 4, 5, 6, 7, 8, 9]"
            :page-size="size"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <AddEmployee :show-dialog.sync="isShow" @add-employee="getUserList" />
      <!-- 分享展示, 预览的二维码的弹层 -->
      <el-dialog
        width="300px"
        title="二维码"
        :visible="showCodeDialog"
        @close="closeDialog"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { reqGetUserList, reqDelEmployee } from '@/api/employees'
import obj from '@/constant/employees'
import AddEmployee from './components/AddEmployee.vue'
import dayjs from 'dayjs'
import errorImg from '@/assets/common/bigUserHeader.png'
import QrCode from 'qrcode'
import AssignRole from './components/AssignRole.vue'
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  data() {
    return {
      defaultImg:
        'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      errorImg,
      page: 1,
      size: 5,
      list: [],
      total: 0,
      loading: false,
      hireType: obj.hireType,
      isShow: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      this.loading = true
      const {
        data: { rows, total }
      } = await reqGetUserList(this.page, this.size)
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleSizeChange(val) {
      // console.log('每页条数', val)
      this.size = val
      this.page = 1
      this.getUserList()
    },
    handleCurrentChange(val) {
      // console.log('当前页', val)
      this.page = val
      this.getUserList()
    },
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    formatEmployment(row, column, cellValue, index) {
      const res = this.hireType.find((item) => item.id === +cellValue)
      return res ? res.value : '未知'
    },
    del(id) {
      this.$confirm('确定要删除该员工么,操作不可逆哟?', '温馨提示')
        .then(async() => {
          await reqDelEmployee(id)
          // console.log(res)
          this.$message.success('删除成功')
          if (this.list.length === 1 && this.page > 0) {
            this.page--
          }
          this.getUserList()
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    async handleExport() {
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const {
        data: { rows }
      } = await reqGetUserList(1, this.total)
      console.log(rows)

      const resultsArr = this.formatFn(rows, headersArr, headersRelations)
      console.log(resultsArr)

      import('@/vendor/Export2Excel').then((excel) => {
        console.log(excel)
        excel.export_json_to_excel({
          // 表格的表头
          header: headersArr,
          // 表格的主体数据(固定格式->二维数组)
          data: resultsArr,
          filename: '学生信息表',
          autoWidth: true, // 宽度自适应 非必填
          bookType: 'xlsx' // 文件格式 非必填
        })
      })
    },
    formatFn(rows, headersArr, headersRelations) {
      const list = []
      rows.forEach((item1) => {
        const arr = []
        headersArr.forEach((item2) => {
          const englishKey = headersRelations[item2]
          // 处理
          let val = item1[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            val = dayjs(val).format('YYYY年MM月DD日')
          }
          if (englishKey === 'formOfEmployment') {
            const { hireType } = obj
            const resultObj = hireType.find((v) => v.id === +val)
            val = resultObj ? resultObj.value : '未知'
          }
          arr.push(val)
        })
        list.push(arr)
      })
      return list
    },
    closeDialog() {
      this.showCodeDialog = false
    },
    clickShowCodeDialog(url) {
      if (!url) return
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    handleRoleAssign(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    checkBtnAccess(str) {
      const roles = this.$store.getters.roles
      if (roles) {
        return roles.points.includes(str)
      } else {
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
